/*连接设备*/
import {util} from '../../../js/utlis/util.js';                                           /*公共工具类js*/
import {route} from '../../../js/utlis/route.js';                                         /*页面路由js*/
import {Bluetooth} from '../../../js/utlis/bluetooth.js';                                 /*公共蓝牙类js*/
import {Lan} from '../../../js/utlis/wifi/lan.js';                                        /*公共WIFI类js*/
import {os} from '../../../../hos/os.js';                                                 /*app底层接口调用*/
let bluetooth = null,//连接蓝牙
    bluetoothOther = null;
let lan=null;
class CapacityConnect{
    constructor(){
        this.data={};//页面显示数据
        this.cacheData={//缓存数据
            deviceBlueList:[],//蓝牙设备列表
            deviceLanList:[],//wifi设备列表
            connectSelFlag: false,//连接标志
        };
    }
    /**
     * 生命周期函数--监听页面加载
     * options:页面传入参数
     */
    onLoad(options) {
        let than=this;
        than.pageId=route.globalData.history[route.globalData.history.length-1].id;//当前页id
        than.pageNode=$("#"+this.pageId);
        than.data=JSON.stringify(than.cacheData);//将数据缓存
        than.pageVue=null;//页面vue
        //当前页面引用
        than.pageVue=new Vue({
            el:"#"+than.pageId,
            data:JSON.parse(than.data),//传值赋值
            methods:{//方法
                init:function(){
                    this.leaveFlag = false;//是否离开页面 false：未离开  true:离开
                    this.connectFlag = true;//是否可连接 true:可连接  false:不可连接(正在连接)
                    this.options=options;

                    //获取存储手环
                    this.bracelet=localStorage.getItem('bracelet');
                    if(this.bracelet){
                        this.bracelet=JSON.parse(this.bracelet);
                    }
                },
                backtrack:function(){//返回按钮
                    window.app.backtrack();
                },
                networkingLogic:function(){//设备配网
                    lan.stopLanDevices();//停止扫描
                    bluetooth.stopBluetoothDevices();
                    route.navigateLogic('navigateTo','capacityWifiNetworking');
                },

                /**
                 * 选择设备
                 */
                connectSelLogic:function(type,index){
                    if(type=='blue'){
                        //蓝牙设备
                        this.connectSelPackaging(this.deviceBlueList,type,index);
                        this.connectSelPackaging(this.deviceLanList,type);
                    }else{
                        //wifi设备
                        this.connectSelPackaging(this.deviceBlueList,type);
                        this.connectSelPackaging(this.deviceLanList,type,index);
                    }
                },

                /**
                 * 连接按钮
                 */
                connectDevice:function(){
                    let _this=this,
                        connectObj = CapacityConnect.getConnectList(_this.deviceBlueList,_this.deviceLanList);//连接的设备
                    if (_this.connectFlag){
                        if(_this.connectSelFlag){
                            _this.connectFlag = false;
                            window.app.bluetoothArr = [];
                            bluetoothOther = null;
                            if(connectObj.type=='blue'){
                                //连接蓝牙设备
                                let connectItem = connectObj.connectList[0],
                                    bluetoothArr=[bluetooth];
                                bluetooth.stopBluetoothDevices();//停止扫描
                                //河马的秤是用广播处理
                                if (connectItem.type == "Steelyard" && connectItem.company == "00" && (connectItem.localName =="Hnk_scales"||connectItem.localName =="Hscales")){
                                    _this.connectFlag = true;
                                    bluetooth.closeBluetoothAdapter(true);//关闭蓝牙模块
                                    bluetooth.connectPacket = connectItem;//当前连接设备
                                    window.app.bluetoothArr=[bluetooth];
                                    //route.navigateLogic("navigateTo","capacityScalesBroadcast");
                                    route.navigateLogic("navigateTo","capacityScalesGame");
                                }else{
                                    if (connectObj.connectList[1]) {
                                        bluetoothOther = new Bluetooth();
                                        bluetoothArr.push(bluetoothOther);
                                    }
                                    CapacityConnect.connectDeviceLogic(connectObj.connectList, bluetoothArr, 0,function(res){
                                        _this.connectFlag = true;
                                        if (res.retCode == 1) {
                                            if (!_this.leaveFlag) {//页面没卸载
                                                bluetooth.onWXDeviceBindStateChange(); //加上断开监听事件
                                                lan.closeLanAdapter();//关闭wifi
                                                if (connectObj.connectList.length == 1) {
                                                    let type = window.app.bluetoothArr[0].connectPacket.type;
                                                    if (type == "Smartband") {//手环
                                                        if(_this.bracelet){//判断是否是新手环  新手环没有配对
                                                            if(window.app.bluetoothArr[0].connectPacket.advertis!=_this.bracelet.advertis){
                                                                localStorage.setItem("braceletPair",0);//存储手环
                                                            }
                                                        }
                                                        _this.bracelet = bluetooth.connectPacket;
                                                        localStorage.setItem("bracelet",JSON.stringify(_this.bracelet));//存储手环
                                                        route.navigateLogic("navigateTo","capacitySmartbandGame");
                                                    } else if (type == "Steelyard") {//秤

                                                    }else if (type == "FasciaGun") {//筋膜枪
                                                        route.navigateLogic("navigateTo","capacityGunIndex");
                                                    }  else {//健身设备
                                                        if (type == 'Bicycle' || type == 'Treadmill' || type == 'Cycling' || type == 'RowingMachine' || type == 'Walkingpad'){
                                                            if(_this.options && _this.options.type=='game'){
                                                                if(_this.options.gameId=='atsea'){
                                                                    route.navigateLogic('navigateTo','capacityGameGameAtsea',_this.options);
                                                                }else if(_this.options.gameId=='city'){
                                                                    route.navigateLogic('navigateTo','capacityGameGameCity',_this.options);
                                                                }
                                                            }else{
                                                                route.navigateLogic("navigateTo","capacityClassify");
                                                            }
                                                        }else{
                                                            route.navigateLogic("navigateTo","capacityClassify");
                                                        }
                                                    }
                                                }else{
                                                    let bracelet=null,
                                                        type='';
                                                    if (bluetooth.connectPacket.type == "Smartband") {
                                                        bracelet=bluetooth.connectPacket;
                                                        type=bluetoothOther.connectPacket.type;
                                                    } else {
                                                        bracelet=bluetoothOther.connectPacket;
                                                        type=bluetooth.connectPacket.type;
                                                    }
                                                    if(_this.bracelet){//判断是否是新手环  新手环没有配对
                                                        if(bracelet.advertis!=_this.bracelet.advertis){
                                                            localStorage.setItem("braceletPair",0);//存储手环
                                                        }
                                                    }
                                                    _this.bracelet=bracelet;
                                                    localStorage.setItem("bracelet",JSON.stringify(_this.bracelet));//存储手环
                                                    //后期加上手环本地存储
                                                    if (type == 'Bicycle' || type == 'Treadmill' || type == 'Cycling' || type == 'RowingMachine' || type == 'Walkingpad'){
                                                        if(_this.options && _this.options.type=='game'){
                                                            if(_this.options.gameId=='atsea'){
                                                                route.navigateLogic('navigateTo','capacityGameGameAtsea',_this.options);
                                                            }else if(_this.options.gameId=='city'){
                                                                route.navigateLogic('navigateTo','capacityGameGameCity',_this.options);
                                                            }
                                                        }else{
                                                            route.navigateLogic("navigateTo","capacityClassify");
                                                        }
                                                    }else{
                                                        route.navigateLogic("navigateTo","capacityClassify");
                                                    }
                                                }
                                            }
                                        }else{
                                            bluetooth.closeBLEConnection();//断开连接
                                            if (connectObj.connectList[1]) bluetoothOther.closeBLEConnection();//断开连接
                                            window.app.bluetoothArr = [];
                                            os.makeToast('连接失败',2000);
                                        }
                                    });
                                }
                            }else{
                                //连接wifi设备
                                lan.connectPacket=connectObj.connectList[0];
                                lan.createLanConnection(function(res){
                                    if(res.retCode==1){//连接成功
                                        lan.stopLanDevices();//停止扫描
                                        bluetooth.closeBluetoothAdapter(true);//关闭蓝牙模块
                                        window.app.bluetoothArr=[lan];
                                        route.navigateLogic("navigateTo","capacityWifiClassify");
                                    }else{
                                        os.makeToast('设备连接失败...',2000);
                                    }
                                    _this.connectFlag = true;
                                });
                                /*lan.connectPacket=connectObj.connectList[0];
                                lan.createLanConnection(function(res){
                                    if(res.retCode==1){//连接成功
                                        lan.stopLanDevices();//停止扫描
                                        lan.onWXDeviceBindStateChange(); //加上断开监听事件
                                        window.app.bluetoothArr=[lan];
                                        route.navigateLogic("navigateTo","capacityWifiClassify");
                                    }else{
                                        lan.closeLanConnection();//断开连接
                                        os.makeToast('设备连接失败...',2000);
                                    }
                                    _this.connectFlag = true;
                                });*/
                            }
                        }else{
                            //重新扫描
                            bluetooth.stopBluetoothDevices();//停止扫描
                            bluetooth.closeBluetoothAdapter(true);//关闭蓝牙模块
                            lan.stopLanDevices();//停止WIFI扫描
                            //重新扫描定时
                            if(_this.refreshDeviceTimerID) clearTimeout(_this.refreshDeviceTimerID);
                            _this.refreshDeviceTimerID=setTimeout(function(){
                                _this.refreshDevice();//重新搜索设备
                            },2000);
                        }
                    }else{
                        os.makeToast('设备连接中...',2000);
                    }

                },

                /**
                 * 刷新,重新扫描
                 */
                refreshDevice:function(){
                    let _this=this;
                    _this.deviceBlueList=[];
                    _this.connectSelFlag=false;
                    if (_this.bracelet) {
                        _this.bracelet.sel = false;
                        _this.deviceBlueList.push(_this.bracelet);//添加手环
                    }
                    //蓝牙
                    bluetooth.startBluetoothDevices(500);
                    //++++[
                    let callback = function(devices){
                        let isDirty = false;
                        if(devices.length>0){
                            devices=CapacityConnect.packagingDevices(devices);
                            if(devices.length>0){
                                //去除相同设备
                                if (_this.deviceBlueList.length>0){
                                    for (let i = 0; i < devices.length; i++) {
                                        let sameFlag = true,//没有相同
                                            device={};
                                        let deviceListIndex=0;
                                        for (let j = 0; j < _this.deviceBlueList.length; j++) {
                                            if(_this.deviceBlueList[j].uuid==devices[i].uuid){//通过uuid去重
                                                sameFlag=false;
                                                deviceListIndex=j;
                                                break;
                                            }
                                        }
                                        if (sameFlag) {
                                            devices[i].updateTime = new Date().getTime();
                                            _this.deviceBlueList.push(devices[i]);
                                            isDirty = true;
                                            console.log('Find a new ble device:', devices[i]);
                                        }else{
                                            let updateTime = _this.deviceBlueList[deviceListIndex].updateTime || new Date().getTime();
                                            if ((new Date().getTime() - updateTime) < 1000) {
                                                // TODO 如果设备名称发生了变化不受刷新时间限制
                                                console.log('Limit update ble device:', devices[i], new Date().getTime(), updateTime, _this.deviceBlueList[deviceListIndex].updateTime );
                                                continue;
                                            }
                                            devices[i].sel = _this.deviceBlueList[deviceListIndex].sel;
                                            _this.deviceBlueList[deviceListIndex].updateTime  = new Date().getTime();
                                            _this.deviceBlueList[deviceListIndex]=devices[i];
                                            isDirty = true;
                                            console.log('Update ble device:', devices[i]);
                                        }
                                    }
                                }else{
                                    _this.deviceBlueList = _this.deviceBlueList.concat(devices);
                                }
                                if (isDirty) {
                                    //通过信号排序
                                    _this.deviceBlueList.sort(function (a, b) {
                                        return b.rssi - a.rssi;
                                    });
                                }
                            }
                        }
                    }
                    bluetooth.onBluetoothDeviceFound(callback);
                    bluetooth.getBluetoothDevices(callback());
                    //++++]
                    // ----[
                    // bluetooth.onBluetoothDeviceFound(function(devices){
                    //     if(devices.length>0){
                    //         devices=CapacityConnect.packagingDevices(devices);
                    //         if(devices.length>0){
                    //             //去除相同设备
                    //             if (_this.deviceBlueList.length>0){
                    //                 for (let i = 0; i < devices.length; i++) {
                    //                     let sameFlag = true,//没有相同
                    //                         device={};
                    //                     let deviceListIndex=0;
                    //                     for (let j = 0; j < _this.deviceBlueList.length; j++) {
                    //                         if(_this.deviceBlueList[j].uuid==devices[i].uuid){//通过uuid去重
                    //                             sameFlag=false;
                    //                             deviceListIndex=j;
                    //                             break;
                    //                         }
                    //                     }
                    //                     if (sameFlag) {
                    //                         _this.deviceBlueList.push(devices[i]);
                    //                     }else{
                    //                         devices[i].sel = _this.deviceBlueList[deviceListIndex].sel;
                    //                         _this.deviceBlueList[deviceListIndex]=devices[i]
                    //                     }
                    //                 }
                    //             }else{
                    //                 _this.deviceBlueList = _this.deviceBlueList.concat(devices);
                    //             }
                    //             //通过信号排序
                    //             _this.deviceBlueList.sort(function (a, b) {
                    //                 return b.rssi - a.rssi;
                    //             });
                    //         }
                    //     }
                    // });
                    //]----
                    //WIFI
                    _this.deviceLanList=[];
                    lan.startLanDevices(function(res){//扫描设备
                        if(res.retCode==1){
                            let sameFlag=true,//没有相同
                                device=res.res;
                            let devices=CapacityConnect.packagingDevices([device]);
                            if(devices.length>0){
                                device=devices[0];
                                for (let j = 0; j < _this.deviceLanList.length; j++) {
                                    if(_this.deviceLanList[j].advertis==device.advertis){//通过uuid去重
                                        sameFlag=false;
                                        break;
                                    }
                                }
                                if(sameFlag){
                                    _this.deviceLanList.push(device);
                                }
                            }
                        }else{
                            os.makeToast('扫描设备失败',2000);
                        }
                    });
                    //打开udp扫描消耗资源,5秒后停止扫描设备,如果没有找到设备需要重新扫描
                    /*if(_this.startLanId) clearTimeout(_this.startLanId);
                    _this.startLanId=setTimeout(function(){
                        lan.stopLanDevices();
                    },5000);*/

                    if(_this.deviceTimingId) clearTimeout(_this.deviceTimingId);//清除定时
                    _this.deviceTimingId=setTimeout(function(){
                        if (_this.deviceBlueList.length == 0 && _this.deviceLanList.length == 0) {
                            os.makeToast('没有扫描到设备,请打开蓝牙或WIFI',2000);
                        }
                    },10000);

                },

                /**
                 * 处理选择连接设备
                 */
                connectSelPackaging:function(arr,type,index=-1){
                    let device = [],
                        verify = true;//校验是否通过
                    if(index!=-1) device=arr[index];
                    for(let i=0;i<arr.length;i++){
                        if(index==-1){
                            arr[i].sel=false;
                        }else{
                            if(type=='blue'){
                                if ((arr[i].uuid == device.uuid) && arr[i].sel) {
                                    verify = false;
                                    arr[i].sel = false;
                                }else{
                                    if (device.type =="Steelyard" || device.type =="FasciaGun"){//秤只能连接一个
                                        arr[i].sel = false;
                                        verify=true;
                                    }else{
                                        if (device.type == "Smartband") {//选择手环
                                            if (arr[i].type == "Smartband" || arr[i].type =="Steelyard" || arr[i].type =="FasciaGun") {
                                                arr[i].sel = false;
                                            }
                                        } else {//选择不是手环
                                            if (arr[i].type != "Smartband") {
                                                arr[i].sel = false;
                                            }
                                        }
                                    }
                                }
                            }else{
                                //wifi设备
                                if (arr[i].uuid == device.uuid){
                                    if(arr[i].sel) arr[i].sel=false;
                                    else arr[i].sel=true;
                                }else{
                                    arr[i].sel=false;
                                }
                            }

                        }
                    }
                    if(type=='blue' && verify) arr[index].sel = true;
                    this.connectSelFlag = CapacityConnect.getConnectList(this.deviceBlueList,this.deviceLanList).connectList.length == 0 ? false : true;
                }
            },
        });
        than.pageVue.init();

    }
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let _this=this;
        if(_this.pageVue){
            _this.pageVue.deviceBlueList=[];
            _this.pageVue.connectSelFlag=false;
            window.app.bluetoothArr = [];
            if(bluetooth){
                bluetooth.stopBluetoothDevices();
                bluetooth.closeBluetoothAdapter(true);//关闭蓝牙模块
            }
            if(bluetoothOther){
                bluetoothOther.stopBluetoothDevices();
                bluetoothOther.closeBluetoothAdapter(true);//关闭蓝牙模块
            }

            _this.pageVue.deviceLanList=[];
            _this.pageVue.connectSelFlag=false;
            if(lan){
                lan.closeLanAdapter();//关闭wifi模块
            }
            _this.pageVue.scanTimerId=setTimeout(function(){ //监听设备信息
                bluetoothOther=null;
                bluetooth=new Bluetooth();
                lan=new Lan();
                lan.init();
                _this.pageVue.refreshDevice();//重新搜索设备
            },1000);
        }
    }
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
    }
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        try {
            this.pageVue.leaveFlag = true;
            if(bluetooth){
                bluetooth.stopBluetoothDevices();//停止扫描
                bluetooth.closeBluetoothAdapter(true);//关闭蓝牙模块
            }
            clearTimeout(this.pageVue.deviceTimingId);
            clearTimeout(this.pageVue.refreshDeviceTimerID);
            clearTimeout(this.pageVue.scanTimerId);
            if(bluetoothOther){
                bluetoothOther.stopBluetoothDevices();//停止扫描
                bluetoothOther.closeBluetoothAdapter(true);//关闭蓝牙模块
            }
            if(lan){
                lan.closeLanAdapter();//关闭蓝牙模块
                lan=null;
            }
        }catch(err){
            console.log(err);
        }
    }

    //连接设备方法 设备队列连接， 不能同时连接多个
    static connectDeviceLogic(deviceArr, bluetoothArr, index, callback){
        if(index<bluetoothArr.length){
            bluetoothArr[index].connectPacket = deviceArr[index];//当前连接设备
            bluetoothArr[index].createBLEConnection(function (res) {
                if (res.retCode == 1) {
                    window.app.bluetoothArr.push(bluetoothArr[index]);
                    index++;
                    if(index<bluetoothArr.length){
                        CapacityConnect.connectDeviceLogic(deviceArr, bluetoothArr, index, callback);
                    }else{
                        if(callback) callback(res);
                    }
                } else {
                    if(callback) callback(res);
                }
            });
        }
    }

    //二次封装设备列表数据
    static packagingDevices(devices){
        for (let i = 0; i < devices.length;i++){
            if(devices[i].company=='00' && parseInt(devices[i].advertis.substring(4,6),16)==0xff){
                devices.splice(i,1);
            }else{
                devices[i].eqtObj = util.getEqtObj(1, devices[i].type);
                devices[i].companyObj = util.getCompany(devices[i].company);
                devices[i].sel=false;
                if(devices[i].uuid) devices[i].id=devices[i].uuid;//蓝牙
                else devices[i].id = util.decimalismArrToHex(devices[i].mac);//wifi
            }

        }
        return devices;
    }

    /**
     * 获取连接的设备
     * arr1:蓝牙设备
     * arr2:WIFI设备
     */
    static getConnectList(arr1,arr2){
        let obj={type:'',connectList:[]};
        for (let i = 0; i < arr1.length; i++) {
            if (arr1[i].sel) {
                obj.connectList.push(arr1[i]);
                obj.type='blue';
            }
        }
        for (let i = 0; i < arr2.length; i++) {
            if (arr2[i].sel) {
                obj.connectList.push(arr2[i]);
                obj.type='lan';
            }
        }
        return obj;
    }

}


export{CapacityConnect}

